#!/usr/bin/python
# -*- coding: utf-8 -*-
# This is the main engine for the photo digester.
# it loads a configuration file, and runs all the plugins in the right order

from __future__ import absolute_import

from . import logger, context, plugin, configobj

from engine.plugins.copytostagingplugin import CopyToStagingPlugin
from engine.plugins.renamewithexiftoolplugin import RenameWithExiftoolPlugin


class Engine(object):
    
    def __init__(self,configFileName, theLogger):
        self._theConfigFileName = configFileName
        self._theLogger = theLogger
        self._theConfiguration = None
        self._theContext = None
        self._pluginsToRun= (CopyToStagingPlugin(),RenameWithExiftoolPlugin())

    def Run(self):
        self._theLogger.Info("ça va bouillir")
        self.LoadConfigurationFile()
        self.InitContext()
        self.ExecuteAllPlugins()
        # 1 Charger le fichier de config
        # 2 initialiser le context
        # 3 executer tous les plugins
        
    
    def LoadConfigurationFile(self):
        self._theLogger.Debug("Je vais chager le fichier de configuration")
        self._theConfiguration = configobj.ConfigObj(self._theConfigFileName)
        cameraId = self._theConfiguration['Global']['CameraId']
        self._theLogger.Debug("Config file chargé %s", (cameraId ) )
        
        
    
    def InitContext(self):
        self._theContext = context.Context(self._theLogger)
        pass
    
    def ExecuteAllPlugins(self):
        self._theLogger.Info("On va exécuter tous les plugins")
        self._theLogger.Start(self._pluginsToRun.__len__())
        for plug in self._pluginsToRun:
            self.ExecuteOnePlugin(plug)
        self._theLogger.End()
        
    
    def ExecuteOnePlugin(self,plug):
        plug.Init(self._theContext,self._theConfiguration)
        plug.Start()
        jobData = plug.ComputeSteps()
        self._theLogger.StartStep(jobData.__len__())
        for img in jobData:
            plug.ExecuteStep(img)
        plug.End()
        plug.CleanUpContext()
        self._theLogger.EndStep()

#    for i in xrange(5):
#        log.StartImage("Image-%s" % (i))
#        log.EndImage()
#    log.EndStep()
#    log.StartStep(3)
#    for i in xrange(3):
#        log.StartImage("Image-%s" % (i))
#        log.EndImage()
#    log.EndStep()
#    log.End()

        